import React, { FC, ReactElement, useCallback, useEffect, useReducer } from 'react'
import TdInput from './Input'
import List from './List'
import { todoReducer } from './reducer'
import { ACTION_TYPE, IState, ITodo } from './typings'

//方法一
// const initState: IState = {
//     todoList: []
// }
//方法二 惰性初始化
function init(initTodoList: ITodo[]): IState {
    return {
        todoList: initTodoList
    }
}
const TodoList: FC = (): ReactElement => {
    //方法一
    // const [state, dispatch] = useReducer(todoReducer, initState)
    //方法二 惰性初始化 在useReducer使用的时候再初始化
    const [state, dispatch] = useReducer(todoReducer, [], init)

    useEffect(() => {
        const todoList = JSON.parse(localStorage.getItem('todolist') || '[]')
        console.log(todoList);
        
        dispatch({
            type: ACTION_TYPE.INIT_TODOLIST,
            payload: todoList
        })
    }, [])

    useEffect(() => {
        localStorage.setItem('todolist', JSON.stringify(state.todoList))
    }, [state.todoList])

    const addTodo = useCallback((todo: ITodo): void => {
        dispatch({
            type: ACTION_TYPE.ADD_TODO,
            payload: todo
        })
        // setTodoList(state.todoList => [...todoList, todo])
    }, [])

    const toggleTodo = useCallback((id: number): void => {
        dispatch({
            type: ACTION_TYPE.TOGGLE_TODO,
            payload: id
        })
    }, [])
    const removeTodo = useCallback((id: number): void => {
        dispatch({
            type: ACTION_TYPE.REMOVE_TODO,
            payload: id
        })
    }, [])
    return (
        <div className="todo-list">
            <TdInput
                addTodo={addTodo}
                todoList={state.todoList}
            />
            <List
                todoList={state.todoList}
                toggleTodo={toggleTodo}
                removeTodo={removeTodo}
            />
        </div>
    )
}

export default TodoList;